package com.jn.zhinongbao.adapter;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

import com.example.supportingagriculturaltreasures.adapter.MerchantPagerAdapter;
import com.example.supportingagriculturaltreasures.bean.User;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.example.supportingagriculturaltreasures.utils.PreferenceManager;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MerchantActivity extends AppCompatActivity {

    private ViewPager2 viewPager;
    private BottomNavigationView bottomNavigation;
    private PreferenceManager preferenceManager;
    private DatabaseHelper databaseHelper;
    private User currentUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_merchant);

        initViews();
        initData();
        setupViewPager();
        setupBottomNavigation();
        loadUserData();
    }

    private void initViews() {
        viewPager = findViewById(R.id.view_pager);
        bottomNavigation = findViewById(R.id.bottom_navigation);
    }

    private void initData() {
        preferenceManager = new PreferenceManager(this);
        databaseHelper = new DatabaseHelper(this);
    }

    private void setupViewPager() {
        MerchantPagerAdapter adapter = new MerchantPagerAdapter(this);
        viewPager.setAdapter(adapter);
        
        // 禁用ViewPager2的滑动，让用户只能通过底部导航切换
        viewPager.setUserInputEnabled(false);
    }

    private void setupBottomNavigation() {
        bottomNavigation.setOnItemSelectedListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.nav_merchant_home) {
                viewPager.setCurrentItem(0);
                return true;
            } else if (itemId == R.id.nav_farmer_circle) {
                viewPager.setCurrentItem(1);
                return true;
            } else if (itemId == R.id.nav_merchant_publish) {
                viewPager.setCurrentItem(2);
                return true;
            } else if (itemId == R.id.nav_merchant_message) {
                viewPager.setCurrentItem(3);
                return true;
            } else if (itemId == R.id.nav_merchant_profile) {
                viewPager.setCurrentItem(4);
                return true;
            }
            return false;
        });

        // 设置默认选中首页
        bottomNavigation.setSelectedItemId(R.id.nav_merchant_home);
    }

    private void loadUserData() {
        int userId = preferenceManager.getCurrentUserId();
        if (userId != -1) {
            currentUser = databaseHelper.getUserById(userId);
            if (currentUser != null) {
                // 设置ActionBar标题显示店铺名称
                String title = currentUser.getShopName() != null ? 
                        currentUser.getShopName() : currentUser.getUsername() + "的店铺";
                if (getSupportActionBar() != null) {
                    getSupportActionBar().setTitle(title);
                }
                
                // 显示欢迎信息
                Toast.makeText(this, "欢迎回来，" + currentUser.getUsername(), Toast.LENGTH_SHORT).show();
            } else {
                // 用户信息获取失败，退出到登录页面
                Toast.makeText(this, "用户信息获取失败，请重新登录", Toast.LENGTH_LONG).show();
                performLogout();
            }
        } else {
            // 没有用户ID，退出到登录页面
            Toast.makeText(this, "登录状态已失效，请重新登录", Toast.LENGTH_LONG).show();
            performLogout();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.merchant_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_logout) {
            showLogoutConfirmDialog();
            return true;
        } else if (id == R.id.action_settings) {
            Toast.makeText(this, "设置功能开发中...", Toast.LENGTH_SHORT).show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 显示退出登录确认对话框
     */
    private void showLogoutConfirmDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("退出登录")
                .setMessage("确定要退出登录吗？")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        performLogout();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setCancelable(true)
                .show();
    }

    /**
     * 执行退出登录操作
     */
    private void performLogout() {
        try {
            // 获取用户名用于告别消息
            String username = currentUser != null ? currentUser.getUsername() : "用户";
            
            // 清除登录信息
            preferenceManager.clearUserLogin();
            
            // 跳转到登录页面，携带退出登录信息
            Intent intent = new Intent(this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.putExtra("fromLogout", true);
            intent.putExtra("logoutMessage", "再见，" + username + "！");
            startActivity(intent);
            
            // 结束当前Activity
            finish();
            
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "退出登录失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 处理返回键，显示退出确认
     */
    @SuppressLint("MissingSuperCall")
    @Override
    public void onBackPressed() {
        showExitConfirmDialog();
    }

    /**
     * 显示退出应用确认对话框
     */
    private void showExitConfirmDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("退出应用")
                .setMessage("确定要退出农业宝藏应用吗？")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setPositiveButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 退出应用
                        finishAffinity();
                        System.exit(0);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setNeutralButton("退出登录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        performLogout();
                    }
                })
                .setCancelable(true)
                .show();
    }
} 